package io.kiki.stack.http.feign.SpringMvcContract.annotation;

import io.kiki.stack.http.feign.MethodMetadata;
import io.kiki.stack.http.feign.SpringMvcContract.AnnotatedParameterProcessor;
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.CookieValue;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.Collections;

import static io.kiki.stack.http.feign.Util.checkState;
import static io.kiki.stack.http.feign.Util.emptyToNull;

/**
 * {@link CookieValue} annotation processor.
 */
public class CookieValueParameterProcessor implements AnnotatedParameterProcessor {

    private static final Class<CookieValue> ANNOTATION = CookieValue.class;

    @Override
    public Class<? extends Annotation> getAnnotationType() {
        return ANNOTATION;
    }

    @Override
    public boolean processArgument(AnnotatedParameterContext annotatedParameterContext, Annotation annotation, Method method) {
        int parameterIndex = annotatedParameterContext.getParameterIndex();
        MethodMetadata methodMetadata = annotatedParameterContext.getMethodMetadata();
        CookieValue cookieValue = ANNOTATION.cast(annotation);
        String name = cookieValue.value().trim();
        checkState(emptyToNull(name) != null, "Cookie.name() was empty on parameter %s", parameterIndex);
        annotatedParameterContext.setParameterName(name);
        String cookieExpression = methodMetadata.template().headers().getOrDefault(HttpHeaders.COOKIE, Collections.singletonList("")).stream().findFirst().orElse("");
        if (cookieExpression.length() == 0) {
            cookieExpression = String.format("%s={%s}", name, name);
        } else {
            cookieExpression += String.format("; %s={%s}", name, name);
        }
        methodMetadata.template().removeHeader(HttpHeaders.COOKIE);
        methodMetadata.template().header(HttpHeaders.COOKIE, cookieExpression);
        return true;
    }

}
